package Classes
{
	import Classes.Actions.IAction;
	
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class UserInterface
	{
		private var m_mouseDown:Boolean = false;
		private var m_mouseDownPoint:Point;
		private var m_mouseUpPoint:Point;	
		private var m_mouseDragVector:Point;	
		
		public var m_stage:Stage;
		
		private var m_display:Sprite = new Sprite;
		private var m_camera:Sprite = new Sprite();
		private var m_world:World;
		
		private var m_currentSkill:Skill;
		
		public function UserInterface()
		{
			var bg:Sprite = new Sprite();
			bg.graphics.beginFill(0xCCCCCC);
			bg.graphics.drawRect(0,0,600,600);
			bg.graphics.endFill();
			
			m_display.addChild(bg);
			
		}

		
		public function setStage(stage:Stage):void{
			m_stage = stage;
			stage.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
			stage.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
			stage.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);	
		}
				
		
		public function getDisplay():Sprite{
			return m_display;
		}
		
		public function setWorld(world:World):void{
			m_world = world;
			m_display.addChild(m_world.getDisplay());
			//m_world.getDisplay().mask = m_camera;
		}

		
		private function onMouseDown(me:MouseEvent):void{
			m_mouseDown = true;
			m_mouseDownPoint = new Point(m_stage.mouseX,m_stage.mouseY);
			

		}
		private function onMouseUp(me:MouseEvent):void{
			m_mouseDown = false;
			m_mouseUpPoint = new Point(m_stage.mouseX,m_stage.mouseY);
			var worldPoint:Point = Main.stage2world(m_mouseUpPoint);
			var entity:Entity = m_world.entityManager.pickEntity(worldPoint);
			if(entity){
				m_currentSkill = m_world.getPlayer().getSkillComponent().getSkillByName('fireball',entity);
				if(!m_currentSkill.isInRange()){
					m_world.getPlayer().getRigidBodyComponent().moveTo(entity.getRigidBodyComponent().getPosition(),m_currentSkill.range);
					m_world.getPlayer().addEventListener(GameEvent.DESTINATION_REACHED, onTargetInRange);
				}
				else if(!m_currentSkill.isCasting()){
					m_currentSkill.cast();	
				}
			} else {
				Main.actionManager.addMoveAction(new Point(m_mouseUpPoint.x/Main.P2WSCALE, m_mouseUpPoint.y/Main.P2WSCALE));	
			}			 
		}
		
		private function onTargetInRange(ge:GameEvent):void{
			var player:Entity = ge.currentTarget as Entity;
			if(!m_currentSkill.isCasting()){
				m_currentSkill.cast();	
			}
			
		}
		private function onMouseMove(me:MouseEvent):void{
			if(m_mouseDown){
				var curPoint:Point = new Point(m_stage.mouseX,m_stage.mouseY);
				m_mouseDragVector = curPoint.subtract(m_mouseDownPoint);
			}
		}	
		
	}
}